package org.ehe.business.bom.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.ehe.business.bom.domain.BomMaster;
import org.ehe.business.bom.domain.BomStructure;
import org.ehe.business.bom.domain.BomVersion;
import org.ehe.business.bom.domain.dto.BomCreationRequest;
import org.ehe.business.bom.mapper.BomMasterMapper;
import org.ehe.business.bom.service.*;
import org.ehe.business.drawing.domain.DesignDrawing;
import org.ehe.business.drawing.domain.vo.DesignDrawingVO;
import org.ehe.business.drawing.service.DesignDrawingService;
import org.ehe.business.overdue.config.OverdueStatus;
import org.ehe.common.core.constant.StatusEnum;
import org.ehe.common.core.domain.dto.StartProcessDTO;
import org.ehe.common.core.domain.dto.StartProcessReturnDTO;
import org.ehe.common.core.service.WorkflowService;
import org.ehe.common.satoken.utils.LoginHelper;
import org.ehe.erp.controller.purchase.ErpPurchaseOrderController;
import org.ehe.erp.domain.purchase.ErpPurchaseOrder;
import org.ehe.erp.domain.purchase.ErpPurchaseOrderItem;
import org.ehe.erp.domain.purchase.bo.ErpPurchaseOrderBo;
import org.ehe.erp.domain.purchase.bo.ErpPurchaseOrderItemBo;
import org.ehe.erp.enums.ErpAuditStatus;
import org.ehe.erp.service.purchase.IErpPurchaseOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * BOM主表实现方法
 * @author :zhangnn
 * @className :BomMasterServiceImpl
 * @description: TODO
 * @date 2025-07-30 13:51:26
 */
@Slf4j
@Service
public class BomMasterServiceImpl extends ServiceImpl<BomMasterMapper, BomMaster> implements BomMasterService {
    @Autowired
    private BomVersionService bomVersionService;

    @Autowired
    private BomStructureService bomStructureService;

    @Autowired
    private IErpPurchaseOrderService erpPurchaseOrderService;

    @Autowired
    private DesignDrawingService designDrawingService;

    @Autowired
    private WorkflowService workflowService;


    /**
     * 创建新的BOM主表记录
     */
    @Transactional
    public BomMaster createBomMaster(BomCreationRequest request) {
        BomMaster bomMaster = new BomMaster();

        // 设置BOM编码
        bomMaster.setBomCode(request.getBomCode());
        bomMaster.setBomName(request.getBomName());
        bomMaster.setStatus(StatusEnum.CG.getCode());
        bomMaster.setApproveStatus(String.valueOf(ErpAuditStatus.PENDING_SUBMIT.getStatus()));//草稿
        bomMaster.setProjectId(request.getProjectId());
        bomMaster.setProjectName(request.getProjectName());
        bomMaster.setSolutionId(request.getSolutionId());
        bomMaster.setSolutionName(request.getSolutionName());
        bomMaster.setEffectiveDate(request.getEffectiveDate());
        bomMaster.setExpireDate(request.getExpireDate());
        bomMaster.setDrawId(request.getDrawId());
        bomMaster.setBomType(1); // 设计BOM
        bomMaster.setCurrentVersion(request.getCurrentVersion() != null ? request.getCurrentVersion() : "1.0");
        bomMaster.setRemark(request.getRemark());
        bomMaster.setIsOverdueEndTime(request.getIsOverdueEndTime());
        bomMaster.setIsOverdue(OverdueStatus.PENDING);
        bomMaster.setCreateBy(LoginHelper.getUsername());
        bomMaster.setTenantId(LoginHelper.getTenantId());
        this.baseMapper.insert(bomMaster);
        log.info("BOM主表记录创建成功: id={}", bomMaster.getId());
        return bomMaster;
    }

    /**
     * 更新BOM主表记录
     */
    @Transactional
    public BomMaster updateBomMaster(BomCreationRequest request) {
        log.info("更新BOM主表记录: id={}, bomCode={}", request.getId(), request.getBomCode());

        // 验证记录存在
        BomMaster existing = this.getById(request.getId());
        if (existing == null) {
            throw new RuntimeException("BOM记录不存在: " + request.getId());
        }
        // 只有草稿、被拒绝状态才能编辑
        if (!ErpAuditStatus.ALLOW_EDIT.contains(Integer.valueOf(existing.getStatus()))) {
            throw new RuntimeException("当前状态不允许编辑，请确认BOM已处于草稿或被拒绝状态");
        }

        existing.setBomCode(request.getBomCode());
        existing.setBomName(request.getBomName());
        existing.setProjectId(request.getProjectId());
        existing.setProjectName(request.getProjectName());
        existing.setSolutionId(request.getSolutionId());
        existing.setSolutionName(request.getSolutionName());
        existing.setEffectiveDate(request.getEffectiveDate());
        existing.setExpireDate(request.getExpireDate());
        existing.setDrawId(request.getDrawId());
        existing.setBomType(1); // 设计BOM
        existing.setCurrentVersion(request.getCurrentVersion() != null ? request.getCurrentVersion() : "1.0");
        existing.setRemark(request.getRemark());
        //预估时常
        existing.setEstimatedHours(request.getEstimatedHours());
        // 更新时间
        existing.setUpdateTime(new Date());

        if(null == existing.getIsOverdueEndTime()){
            existing.setIsOverdueEndTime(request.getIsOverdueEndTime());
        }
        //超期未处理
        if(existing.getIsOverdueEndTime().isBefore(LocalDateTime.now())){
            existing.setIsOverdue(OverdueStatus.OVERDUE_AND_PENDING);
        }
        existing.setUpdateBy(LoginHelper.getUsername());

        // 更新记录
        this.updateById(existing);

        log.info("BOM主表记录更新成功: id={}", existing.getId());
        return existing;
    }

    /**
     * 更新bom时长
     * @param request
     * @return
     */
    @Override
    public BomMaster submitBomDays(BomCreationRequest request) {
        BomMaster bomMaster = this.baseMapper.selectById(request.getId());
        bomMaster.setEstimatedHours(request.getEstimatedHours());
        bomMaster.setTaskDeadline(LocalDateTime.now().plusDays(request.getEstimatedHours()));

        if(bomMaster.getIsOverdueEndTime().isBefore(LocalDateTime.now())){
            bomMaster.setIsOverdue(OverdueStatus.OVERDUE_AND_PROCESSED);
        }
        bomMaster.setStatus(StatusEnum.SHZ.getCode());
        this.baseMapper.updateById(bomMaster);
        return bomMaster;
    }

    /**
     * 完成BOM 提交
     * @param request
     * @return
     */
    @Override
    public BomMaster completeBom(BomCreationRequest request) {
        BomMaster bomMaster = this.baseMapper.selectById(request.getId());
        bomMaster.setStatus(StatusEnum.SHZ_WC.getCode());
        bomMaster.setApproveStatus(ErpAuditStatus.SUBMITTED.getStatus().toString());
        if(bomMaster.getTaskDeadline().isBefore(LocalDateTime.now())){
            bomMaster.setIsTaskTimeout(OverdueStatus.OVERDUE);//已经超时
        }
        this.baseMapper.updateById(bomMaster);

        if(bomMaster.getApproveStatus().equals(ErpAuditStatus.SUBMITTED.getStatus().toString())){
            StartProcessDTO process = new StartProcessDTO();
            Map<String,Object> map = new HashMap<>();
            map.put("type","bomComplete");
            process.setVariables(map);
            //BOM 完成审批流程
            process.setFlowCode("bomComplete");
            process.setBusinessId(String.valueOf(request.getId()));
            StartProcessReturnDTO processReturnDTO = workflowService.startWorkFlow(process);
            log.info("流程审批发起成功，已启动: projectId={}, engineerId={}", request.getId(), bomMaster.getCreateBy());
            workflowService.completeTask(processReturnDTO.getTaskId(),"完成该BOM任务所需时长"+bomMaster.getEstimatedHours()+"天");
        }
        return bomMaster;
    }

    /**
     * 根据项目ID查询BOM列表
     */
    public List<BomMaster> findByProjectId(Long projectId) {
        QueryWrapper<BomMaster> wrapper = new QueryWrapper<>();
        wrapper.eq("project_id", projectId)
            .orderByDesc("create_time");
        return this.list(wrapper);
    }

    /**
     * 根据BOM类型查询BOM列表
     */
    public List<BomMaster> findByBomType(Integer bomType) {
        QueryWrapper<BomMaster> wrapper = new QueryWrapper<>();
        wrapper.eq("bom_type", bomType)
            .eq("status", StatusEnum.YFB.getCode()) // 已发布状态
            .orderByDesc("create_time");
        return this.list(wrapper);
    }

    /**
     * 根据产品编码查询BOM
     */
    public List<BomMaster> findByProductCode(String productCode) {
        QueryWrapper<BomMaster> wrapper = new QueryWrapper<>();
        wrapper.eq("product_code", productCode)
            .orderByDesc("create_time");
        return this.list(wrapper);
    }

    /**
     * 提交BOM审批
     */
    @Transactional
    public BomMaster submitForApproval(Long bomId, Long days,Long workflowInstanceId) {
        log.info("提交BOM审批: bomId={}, workflowInstanceId={}", bomId, workflowInstanceId);

        BomMaster bomMaster = this.getById(bomId);
        if (bomMaster == null) {
            throw new RuntimeException("BOM记录不存在");
        }

        if (!ErpAuditStatus.ALLOW_EDIT.contains(Integer.valueOf(bomMaster.getApproveStatus()))) {
            throw new RuntimeException("当前状态不允许编辑，请确认BOM已处于草稿或被拒绝状态");
        }

        // 更新状态为预警提交
        bomMaster.setStatus(StatusEnum.SHZ.getCode());
        bomMaster.setApproveStatus(ErpAuditStatus.SUBMITTED.getStatus().toString());
        bomMaster.setWorkflowInstanceId(workflowInstanceId);
        bomMaster.setUpdateTime(new Date());
        //已经处理
        bomMaster.setIsOverdue(OverdueStatus.PROCESSED);
        if(null == bomMaster.getIsOverdueEndTime()){
            bomMaster.setIsOverdueEndTime(LocalDateTime.now().plusHours(1));
        }
        if(bomMaster.getIsOverdueEndTime().isBefore(LocalDateTime.now())){
            //超期处理
            bomMaster.setIsOverdue(OverdueStatus.OVERDUE_AND_PROCESSED);
        }
        bomMaster.setEstimatedHours(Math.toIntExact(days));
        bomMaster.setTaskDeadline(LocalDateTime.now().plusDays(bomMaster.getEstimatedHours()));

        this.updateById(bomMaster);

        // 同步更新版本状态
        BomVersion currentVersion = bomVersionService.getCurrentVersion(bomId);
        if (currentVersion != null) {
            currentVersion.setStatus(1);
            currentVersion.setWorkflowInstanceId(workflowInstanceId);
            bomVersionService.updateById(currentVersion);
        }

        log.info("BOM提交审批成功: bomId={}", bomId);

        //发起工作流程-响应
        if(bomMaster.getApproveStatus().equals(ErpAuditStatus.SUBMITTED.getStatus().toString())){
            StartProcessDTO process = new StartProcessDTO();
            Map<String,Object> map = new HashMap<>();
            map.put("type","bom");
            map.put("engineer",LoginHelper.getUserId());
            process.setVariables(map);
            process.setFlowCode("bom");
            process.setBusinessId(String.valueOf(bomId));
            StartProcessReturnDTO processReturnDTO = workflowService.startWorkFlow(process);
            log.info("流程审批发起成功，已启动: projectId={}, engineerId={}", bomId, bomMaster.getCreateBy());
            workflowService.completeTask(processReturnDTO.getTaskId(),"完成该BOM任务所需时长"+bomMaster.getEstimatedHours()+"天");
        }

        return bomMaster;
    }

    /**
     * 审批通过 - 发布BOM
     */
    @Transactional
    public BomMaster approveBom(Long bomId, Long approverId, String code) {
        log.info("审批通过BOM: bomId={}, approverId={}", bomId, approverId);

        BomMaster bomMaster = this.getById(bomId);
        if (bomMaster == null) {
            throw new RuntimeException("BOM记录不存在");
        }

        Date now = new Date();

        // 更新主表状态为 处理中
        bomMaster.setStatus(StatusEnum.CLZ.getCode());
        if (code.equals(StatusEnum.WC.getCode())) {
            bomMaster.setStatus(StatusEnum.WC.getCode());
        }
        bomMaster.setApproveStatus(ErpAuditStatus.APPROVE.getStatus().toString());
        bomMaster.setEffectiveDate(now);
        bomMaster.setUpdateTime(now);
        this.updateById(bomMaster);

        // 更新版本状态为已发布
        BomVersion currentVersion = bomVersionService.getCurrentVersion(bomId);
        if (currentVersion != null) {
            currentVersion.setStatus(ErpAuditStatus.APPROVE.getStatus());
            currentVersion.setEffectiveDate(now);
            currentVersion.setApproverId(approverId);
            currentVersion.setApproverName(LoginHelper.getUsername());
            currentVersion.setApproveTime(now);
            bomVersionService.updateById(currentVersion);
        }

        //BOM完成时候，生成采购订单
        if(code.equals(StatusEnum.WC.getCode())){
            try {
                generatePurchaseOrder(bomId, bomMaster.getDrawId());
                log.info("BOM审批通过并成功生成采购订单: bomId={}", bomId);
            } catch (Exception e) {
                log.error("生成采购订单失败: bomId={}, error={}", bomId, e.getMessage());
                throw new RuntimeException("BOM审批通过但生成采购订单失败: " + e.getMessage());
            }
        }
        log.info("BOM审批通过成功: bomId={}", bomId);
        return bomMaster;
    }

    /**
     * 审批拒绝
     */
    @Transactional
    public BomMaster rejectBom(Long bomId, String rejectReason) {
        log.info("拒绝BOM审批: bomId={}, reason={}", bomId, rejectReason);

        BomMaster bomMaster = this.getById(bomId);
        if (bomMaster == null) {
            throw new RuntimeException("BOM记录不存在");
        }

        if (!bomMaster.getApproveStatus().equals(ErpAuditStatus.PROCESS.getStatus())) {
            throw new RuntimeException("只有审批中的BOM才能拒绝");
        }

        // 恢复为草稿状态
        bomMaster.setStatus(StatusEnum.CG.getCode());
        bomMaster.setApproveStatus(ErpAuditStatus.REJECTED.getStatus().toString());
        bomMaster.setWorkflowInstanceId(null);
        bomMaster.setUpdateTime(new Date());
        this.updateById(bomMaster);

        // 恢复版本状态为草稿
        BomVersion currentVersion = bomVersionService.getCurrentVersion(bomId);
        if (currentVersion != null) {
            currentVersion.setStatus(ErpAuditStatus.REJECTED.getStatus());
            currentVersion.setWorkflowInstanceId(null);
            bomVersionService.updateById(currentVersion);
        }

        log.info("BOM审批拒绝成功: bomId={}", bomId);

        return bomMaster;
    }

    /**
     * 废弃BOM
     */
    @Transactional
    public void obsoleteBom(Long bomId, String obsoleteReason) {
        log.info("废弃BOM: bomId={}, reason={}", bomId, obsoleteReason);

        BomMaster bomMaster = this.getById(bomId);
        if (bomMaster == null) {
            throw new RuntimeException("BOM记录不存在");
        }

        Date now = new Date();

        // 更新主表状态为已废弃
        bomMaster.setStatus(StatusEnum.FQ.getCode());
        bomMaster.setExpireDate(now);
        bomMaster.setRemark(bomMaster.getRemark() + " [废弃原因: " + obsoleteReason + "]");
        bomMaster.setUpdateTime(now);
        this.updateById(bomMaster);

        // 废弃当前版本
        BomVersion currentVersion = bomVersionService.getCurrentVersion(bomId);
        if (currentVersion != null) {
            currentVersion.setStatus(3);
            currentVersion.setExpireDate(now);
            bomVersionService.updateById(currentVersion);
        }

        log.info("BOM废弃成功: bomId={}", bomId);
    }

    /**
     * 基于现有BOM创建新BOM（用于BOM转换：EBOM->PBOM->MBOM）
     */
    @Transactional
    public BomMaster createBomFromExisting(Long sourceBomId, Integer targetBomType,
                                           String newBomCode, String newBomName) {
        log.info("基于已有BOM创建新BOM: sourceBomId={}, targetBomType={}", sourceBomId, targetBomType);

        BomMaster sourceBom = this.getById(sourceBomId);
        if (sourceBom == null) {
            throw new RuntimeException("源BOM不存在");
        }

        if (sourceBom.getStatus() != StatusEnum.YFB.getCode()) {
            throw new RuntimeException("只能基于已发布的BOM进行转换");
        }

        // 创建新的BOM主表记录
        BomMaster newBom = new BomMaster();
        newBom.setBomCode(newBomCode);
        newBom.setBomName(newBomName);
        newBom.setProjectId(sourceBom.getProjectId());
        newBom.setProjectName(sourceBom.getProjectName());

        newBom.setSolutionId(sourceBom.getSolutionId());
        newBom.setSolutionName(sourceBom.getSolutionName());
        newBom.setBomType(targetBomType);
        newBom.setCurrentVersion("1.0");
        newBom.setStatus(StatusEnum.CG.getCode()); // 草稿状态
        newBom.setCreateTime(new Date());
        this.save(newBom);

        // 创建版本记录
        BomVersion newVersion = new BomVersion();
        newVersion.setBomId(newBom.getId());
        newVersion.setVersionCode("1.0");
        newVersion.setVersionName("基于" + getBomTypeName(sourceBom.getBomType()) + "转换");
        newVersion.setVersionType(1);
        newVersion.setStatus(0);
        newVersion.setChangeReason("BOM转换");
        newVersion.setChangeDescription("基于BOM[" + sourceBom.getBomCode() + "]转换为" + getBomTypeName(targetBomType));
        bomVersionService.save(newVersion);

        // 复制BOM结构
        BomVersion sourceVersion = bomVersionService.getCurrentVersion(sourceBomId);
        if (sourceVersion != null) {
            bomStructureService.copyBomStructure(sourceVersion.getId(), newVersion.getId());
        }

        log.info("基于已有BOM创建新BOM成功: newBomId={}", newBom.getId());
        return newBom;
    }

    /**
     * 获取BOM类型名称
     */
    private String getBomTypeName(Integer bomType) {
        switch (bomType) {
            case 1: return "设计BOM";
            case 2: return "工艺BOM";
            case 3: return "制造BOM";
            default: return "未知类型";
        }
    }

    /**
     * 检查BOM编码是否已存在
     */
    public boolean isBomCodeExists(String bomCode) {
        QueryWrapper<BomMaster> wrapper = new QueryWrapper<>();
        wrapper.eq("bom_code", bomCode);
        return this.count(wrapper) > 0;
    }

    /**
     * 获取项目的有效BOM列表
     */
    public List<BomMaster> getEffectiveBomsByProject(Long projectId) {
        QueryWrapper<BomMaster> wrapper = new QueryWrapper<>();
        wrapper.eq("project_id", projectId)
            .eq("status", 2) // 已发布状态
            .isNull("expire_date") // 未失效
            .orderByDesc("create_time");
        return this.list(wrapper);
    }

    /**
     * 根据BOM生成采购订单
     */
    private void generatePurchaseOrder(Long bomId, Long drawId) {
        log.info("开始为BOM生成采购订单: bomId={}", bomId);

        // 获取BOM物料清单
        BomVersion version = bomVersionService.getCurrentVersion(bomId);
        List<BomStructure> bomMaterialList = bomStructureService.getBomMaterialList(version.getId());

        if (CollUtil.isEmpty(bomMaterialList)) {
            log.warn("BOM物料清单为空，无法生成采购订单: bomId={}", bomId);
            return;
        }
//
//        // 按供应商分组生成采购订单
//        Map<Long, List<BomStructure>> supplierGroupMap = bomMaterialList.stream()
//            .filter(item -> item.getSupplierId() != null) // 过滤掉没有供应商的物料
//            .collect(Collectors.groupingBy(BomStructure::getSupplierId));
//
//        if (supplierGroupMap.isEmpty()) {
//            log.warn("BOM物料清单中没有指定供应商的物料，无法生成采购订单: bomId={}", bomId);
//            return;
//        }
//
//        // 为每个供应商创建一个采购订单
//        supplierGroupMap.forEach((supplierId, materials) -> {
//            try {
//                createPurchaseOrderForSupplier(bomId, bomName, supplierId, materials);
//            } catch (Exception e) {
//                log.error("为供应商{}生成采购订单失败: {}", supplierId, e.getMessage());
//                throw new RuntimeException("为供应商" + supplierId + "生成采购订单失败: " + e.getMessage());
//            }
//        });

        log.info("开始为BOM生成采购订单: bomId={}", bomId);
        // 创建一个总的采购订单
        try {
            //当bom完成的时候
            String businessStatus = workflowService.getBusinessStatus(String.valueOf(bomId),"bomComplete");
            if(businessStatus.equals("finish")){
                createPurchaseOrderFromBom(bomId, String.valueOf(drawId), bomMaterialList);
            }
        } catch (Exception e) {
            log.error("为BOM生成采购订单失败: bomId={}, error={}", bomId, e.getMessage());
            throw new RuntimeException("BOM生成采购订单失败: " + e.getMessage());
        }
    }

//    /**
//     * 为指定供应商创建采购订单
//     */
//    private void createPurchaseOrderForSupplier(Long bomId, String bomName, Long supplierId,
//                                                List<BomStructure> materials) {
//        log.info("为供应商{}创建采购订单，物料数量: {}", supplierId, materials.size());
//
//        // 创建采购订单BO
//        ErpPurchaseOrderBo orderBo = new ErpPurchaseOrderBo();
//
//        // 设置基本信息
//        orderBo.setName("BOM[" + bomName + "]采购订单");
//        orderBo.setSupplierId(supplierId);
//        orderBo.setOrderTime(new Date());
//        orderBo.setStatus(ErpAuditStatus.PROCESS.getStatus()); // 待审核状态
//        orderBo.setRemark("由BOM[ID:" + bomId + "]自动生成");
//
//        // 设置默认值
//        orderBo.setDiscountPercent(BigDecimal.ZERO);
//        orderBo.setDiscountPrice(BigDecimal.ZERO);
//        orderBo.setDepositPrice(BigDecimal.ZERO);
//        orderBo.setInCount(BigDecimal.ZERO);
//        orderBo.setReturnCount(BigDecimal.ZERO);
//
//        // 创建订单项列表
//        List<ErpPurchaseOrderItemBo> orderItems = new ArrayList<>();
//
//        BigDecimal totalCount = BigDecimal.ZERO;
//        BigDecimal totalProductPrice = BigDecimal.ZERO;
//        BigDecimal totalTaxPrice = BigDecimal.ZERO;
//
//        for (BomStructure material : materials) {
//            ErpPurchaseOrderItemBo item = new ErpPurchaseOrderItemBo();
//
//            // 设置物料信息
//            item.setProductId(material.getItemId()); // 假设itemId对应productId
//            item.setCount(material.getQuantity());
//            item.setProductPrice(material.getUnitPrice() != null ? material.getUnitPrice() : BigDecimal.ZERO);
//
//            // 计算总价
//            BigDecimal itemTotalPrice = item.getProductPrice().multiply(item.getCount());
//            item.setTotalPrice(itemTotalPrice);
//
//            // 设置税率和税额（这里假设默认税率为13%，实际应该从配置或物料信息中获取）
//            BigDecimal taxPercent = BigDecimal.valueOf(13); // 13%税率
//            item.setTaxPercent(taxPercent);
//            BigDecimal taxPrice = itemTotalPrice.multiply(taxPercent).divide(BigDecimal.valueOf(100), 6, RoundingMode.HALF_UP);
//            item.setTaxPrice(taxPrice);
//
//            item.setRemark("BOM物料[" + material.getItemName() + "]");
//
//            orderItems.add(item);
//
//            // 累计总价
//            totalCount = totalCount.add(item.getCount());
//            totalProductPrice = totalProductPrice.add(itemTotalPrice);
//            totalTaxPrice = totalTaxPrice.add(taxPrice);
//        }
//
//        // 设置总计信息
//        orderBo.setTotalCount(totalCount);
//        orderBo.setTotalProductPrice(totalProductPrice);
//        orderBo.setTotalTaxPrice(totalTaxPrice);
//        orderBo.setTotalPrice(totalProductPrice.add(totalTaxPrice));
//
//        // 设置订单项
//        List<ErpPurchaseOrderItem> purchaseOrderItems = convertBomItemsToPurchaseItems(orderItems);
//        orderBo.setItems(purchaseOrderItems);
//
//        // 调用采购订单服务保存
//        String orderNo = erpPurchaseOrderService.insertByBo(orderBo);
//        log.info("成功为供应商{}创建采购订单，订单号: {}", supplierId, orderNo);
//    }

    /**
     * 根据BOM创建采购订单
     */
    private void createPurchaseOrderFromBom(Long bomId, String drawId, List<BomStructure> materials) {
        log.info("为BOM创建采购订单，物料数量: {}", materials.size());

        // 创建采购订单BO
        ErpPurchaseOrderBo orderBo = new ErpPurchaseOrderBo();

        // 设置基本信息
        DesignDrawing drawing = designDrawingService.getById(drawId);
        orderBo.setName("[" + drawing.getDrawNo() + "]采购订单");
        orderBo.setBomId(bomId);
        //orderBo.setSupplierId(null); // 获取默认供应商ID
        orderBo.setOrderTime(new Date());
        orderBo.setStatus(ErpAuditStatus.PROCESS.getStatus()); // 待审核状态
        orderBo.setRemark("由BOM[ID:" + bomId + "]自动生成");
        orderBo.setParentId(0L);
        // 设置默认值
        orderBo.setDiscountPercent(BigDecimal.ZERO);
        orderBo.setDiscountPrice(BigDecimal.ZERO);
        orderBo.setDepositPrice(BigDecimal.ZERO);
        orderBo.setInCount(BigDecimal.ZERO);
        orderBo.setReturnCount(BigDecimal.ZERO);

        // 创建订单项列表
        List<ErpPurchaseOrderItemBo> orderItems = new ArrayList<>();

        BigDecimal totalCount = BigDecimal.ZERO;
        BigDecimal totalProductPrice = BigDecimal.ZERO;
        BigDecimal totalTaxPrice = BigDecimal.ZERO;

        for (BomStructure material : materials) {
            ErpPurchaseOrderItemBo item = new ErpPurchaseOrderItemBo();

            // 设置物料信息
            item.setProductId(material.getItemId());
            item.setCount(material.getQuantity());
            item.setProductPrice(material.getUnitPrice() != null ? material.getUnitPrice() : BigDecimal.ZERO);

            // 计算总价
            BigDecimal itemTotalPrice = item.getProductPrice().multiply(item.getCount());
            item.setTotalPrice(itemTotalPrice);

            // 设置税率和税额（这里假设默认税率为13%，实际应该从配置或物料信息中获取）
            BigDecimal taxPercent = BigDecimal.valueOf(13); // 13%税率
            item.setTaxPercent(taxPercent);
            BigDecimal taxPrice = itemTotalPrice.multiply(taxPercent).divide(BigDecimal.valueOf(100), 6, RoundingMode.HALF_UP);
            item.setTaxPrice(taxPrice);

            String supplierInfo = material.getSupplierId() != null ?
                " [供应商:" + material.getSupplierName() + "]" : "";
            item.setRemark("BOM物料[" + material.getItemName() + "]" + supplierInfo);

            orderItems.add(item);

            // 累计总价
            totalCount = totalCount.add(item.getCount());
            totalProductPrice = totalProductPrice.add(itemTotalPrice);
            totalTaxPrice = totalTaxPrice.add(taxPrice);
        }

        // 设置总计信息
        orderBo.setTotalCount(totalCount);
        orderBo.setTotalProductPrice(totalProductPrice);
        orderBo.setTotalTaxPrice(totalTaxPrice);
        orderBo.setTotalPrice(totalProductPrice.add(totalTaxPrice));

        // 设置订单项
        List<ErpPurchaseOrderItem> purchaseOrderItems = convertBomItemsToPurchaseItems(orderItems);
        orderBo.setItems(purchaseOrderItems);

        // 调用采购订单服务保存
        ErpPurchaseOrder order = erpPurchaseOrderService.insertByBo(orderBo);
        log.info("成功为BOM创建采购订单，订单号: {}", order.getNo());
    }

    /**
     * 获取默认供应商ID
     * 优先选择出现频率最高的供应商，如果都没有则返回null
     */
    private Long getDefaultSupplierId(List<BomStructure> materials) {
        // 统计供应商出现频率
        Map<Long, Long> supplierCountMap = materials.stream()
            .filter(material -> material.getSupplierId() != null)
            .collect(Collectors.groupingBy(
                BomStructure::getSupplierId,
                Collectors.counting()
            ));

        if (supplierCountMap.isEmpty()) {
            log.warn("BOM物料清单中没有指定供应商，采购订单将不设置供应商");
            return null;
        }

        // 返回出现频率最高的供应商ID
        Long defaultSupplierId = supplierCountMap.entrySet().stream()
            .max(Map.Entry.comparingByValue())
            .map(Map.Entry::getKey)
            .orElse(null);

        log.info("选择默认供应商ID: {}", defaultSupplierId);
        return defaultSupplierId;
    }

    /**
     * 将BOM订单项转换为采购订单项
     */
    private List<ErpPurchaseOrderItem> convertBomItemsToPurchaseItems(List<ErpPurchaseOrderItemBo> bomItems) {
        return bomItems.stream().map(bomItem -> {
            ErpPurchaseOrderItem purchaseItem = new ErpPurchaseOrderItem();
            purchaseItem.setProductId(bomItem.getProductId());
            purchaseItem.setCount(bomItem.getCount());
            purchaseItem.setProductPrice(bomItem.getProductPrice());
            purchaseItem.setTotalPrice(bomItem.getTotalPrice());
            purchaseItem.setTaxPercent(bomItem.getTaxPercent());
            purchaseItem.setTaxPrice(bomItem.getTaxPrice());
            purchaseItem.setRemark(bomItem.getRemark());
            return purchaseItem;
        }).collect(Collectors.toList());
    }
}
